﻿using Furion.DatabaseAccessor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FurStudy.Application
{
    public class JobService : BackgroundService
    {
        // 日志对象
        private readonly ILogger<JobService> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public JobService(ILogger<JobService> logger,
            IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        /// <summary>
        /// 数据库操作注意：如果作用域中对数据库有任何变更操作，需手动调用SaveChanges或带Now结尾的方法。也可以使用Scoped.CreateUow(handler)代替
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // 写日志
            _logger.LogInformation("开始写日志...");

            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;

                // 获取数据库上下文
                var dbContext = Db.GetDbContext(services);

                // 获取仓储
                // var repository = Db.GetRepository<Person>(services);

                // 解析其他服务
                // var otherService = services.GetService<XXX>();
            }

            return Task.CompletedTask;
        }
    }
}
